package cn.fangline.wo.task.akka.actors;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import cn.fangline.base.util.Constants;
import cn.fangline.base.util.StringUtil;
import cn.fangline.wo.model.Agent;
import cn.fangline.wo.model.Corp;
import cn.fangline.wo.model.CorpTemp;
import cn.fangline.wo.model.User;
import cn.fangline.wo.task.akka.messages.AgentHousePage;
import cn.fangline.wo.task.akka.messages.CheckAlive;
import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * Created by 抽离 on 2017/6/22 0022.
 */
public class AgentMerger extends AbstractActor {
    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    private ActorRef houseMaster;

    public AgentMerger(ActorRef houseMaster) {
        this.houseMaster = houseMaster;
    }

    @Override
    public Receive createReceive() {
        return
                receiveBuilder()
                        .match(Agent.class, this::onReceiveAgent)
                        .build();
    }



    private void onReceiveAgent(Agent agent) {
//         User user = (User) queryRunner.query(connection, selectUserSql,  new BeanHandler<User>(User.class),agent.getTel(), agent.getCityId());
//        System.out.println("接收到：" + agent);
            User user = new User();
            user = user.selectOne("tel={0} and city_id={1}", agent.getTel(), agent.getCityId());
            //用户存在的话，只要更新agent
            if(user != null){
//                System.out.println("出现重复的user");
//                System.out.println("agent：" + agent);
//                System.out.println("user:" + user);
                agent.setCorpId(user.getCorpId());
                agent.setUserId(user.getUserId());
                agent.updateById();
                AgentHousePage agentHousePage = new AgentHousePage();
                agentHousePage.setUrl(agent.getUrl());
                agentHousePage.setCityId(agent.getCityId());
                agentHousePage.setCounter(Constants.INITIAL_RETRY_COUNT);
                agentHousePage.setPage(1);
                agentHousePage.setUserId(user.getUserId());
                agentHousePage.setCorpId(user.getCorpId());
                houseMaster.tell(agentHousePage, getSelf());
            }
            //用户不存在，先处理好公司
            else{
                if(StringUtils.isEmpty(agent.getCorp())){//没有公司就所属于其它
//                 Corp corp = queryRunner.query(connection, selectCorpSql, new BeanHandler<Corp>(Corp.class), "其它", agent.getCityId());
                    Corp corp = new Corp();
                    corp = corp.selectOne("corp_name ={0} and city_id={1}", "其它", agent.getCityId());
                    if(corp == null){//没有其它的话，创建其它，并且更新agent
//                     queryRunner.update(connection, addCorpSql, "其它", agent.getCityId(), new Date());
                        corp = new Corp();
                        corp.setCorpName("其它");
                        corp.setCityId(agent.getCityId());
                        corp.setCreateTime(new Date());
                        corp.insert();
                        agent.setCorpId(corp.getCorpId());
                    }
                    agent.setCorpId(corp.getCorpId());
                }
                else{//公司存在，处理公司名
//                 CorpTemp corpTemp = queryRunner.query(connection, selectCorpTempSql, new BeanHandler<CorpTemp>(CorpTemp.class), agent.getCorp(), agent.getCityId());
                    CorpTemp corpTemp = new CorpTemp();
                    corpTemp = corpTemp.selectOne("corp_name ={0} and city_id={1}", agent.getCorp(), agent.getCityId());
                    if(corpTemp != null){//公司临时表里找到了，直接用公司临时表
                        agent.setCorpId(corpTemp.getCorpId());
                    }
                    else{
                        //临时表没有，去公司表找
                        String corpName = StringUtil.processCorpNameNil(agent.getCorp());
//                        Corp corp = queryRunner.query(connection, selectCorpSql, new BeanHandler<Corp>(Corp.class), corpName, agent.getCityId());
                        Corp corp = new Corp();
                        corp = corp.selectOne("corp_name ={0} and city_id={1}", corpName, agent.getCityId());
                        if(corp == null){//公司表也没有，则插入新的公司,同时往临时表添加数据
//                            queryRunner.update(connection, addCorpSql, corpName, agent.getCityId(), new Date());
                            corp = new Corp();
                            corp.setCorpName(corpName);
                            corp.setCityId(agent.getCityId());
                            corp.setCreateTime(new Date());
                            corp.insert();
                            CorpTemp ct = new CorpTemp();
                            ct.setCorpId(corp.getCorpId());
                            ct.setCorpName(agent.getCorp());
                            ct.setCityId(agent.getCityId());
                            ct.setStaffCount(1);
                            ct.insert();
//                            queryRunner.update(connection, addCorpTempSql, ct.getCorpName(), ct.getStaffCount(), ct.getCorpId(), ct.getCityId());
                            agent.setCorpId(corp.getCorpId());
                        }
                        else{
                            agent.setCorpId(corp.getCorpId());
                        }
                    }
                }
                /**
                 * 然后对user进行回填公司ID
                 */
                User u = new User();
                u.setUserName(agent.getAgentName());
                u.setTel(agent.getTel());
                u.setCorpId(agent.getCorpId());
                u.setCityId(agent.getCityId());
                u.setAvatarUrl(agent.getAvatarUrl());
                u.setZone(agent.getZone());
                u.setSection(agent.getSection());
                u.setCreateTime(new Date());
                u.insert();
                agent.setUserId(u.getUserId());
                agent.updateById();
                AgentHousePage agentHousePage = new AgentHousePage();
                agentHousePage.setUrl(agent.getUrl());
                agentHousePage.setCityId(agent.getCityId());
                agentHousePage.setCounter(Constants.INITIAL_RETRY_COUNT);
                agentHousePage.setPage(1);
                agentHousePage.setUserId(u.getUserId());
                agentHousePage.setCorpId(u.getCorpId());
                houseMaster.tell(agentHousePage, getSelf());
            }
    }
}
